<template>
  <div>
    <div class="container">
      <div class="handle-box" style="display: flex">
        <el-input v-model="com.id" class="handle-input mr10">
          <template #prepend>编号</template>
        </el-input>
        <el-input v-model="com.name" class="handle-input mr10">
          <template #prepend>名称</template>
        </el-input>
        <el-input v-model="com.price" class="handle-input mr10">
          <template #prepend>价格</template>
        </el-input>
        <!--        <el-input-->
        <!--            v-model="k.kg_kg"-->
        <!--            class="handle-input mr10"-->
        <!--        >-->
        <!--          <template #prepend>重量</template>-->
        <!--        </el-input>-->
        <el-input v-model="com.num" class="handle-input mr10">
          <template #prepend>数量</template>
        </el-input>
        <el-date-picker
          style="width: 14%; margin-right: 10px"
          v-model="com.date"
          type="date"
          placeholder="生产日期"
          value-format="YYYY-MM-DD"
        >
        </el-date-picker>
        <el-button type="primary" :icon="Search" @click="handleSearch"
          >搜索</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
        stripe
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
          fixed
          prop="id"
          label="商品编号"
          width="80"
          align="center"
        ></el-table-column>
        <el-table-column label="图片" width="150" align="center">
          <template #default="scope">
            <div>
              <el-image
                style="width: 100px; height: 100px"
                :src="getAssetsFile(scope.row.img1)"
                :z-index="999"
                :preview-src-list="[getAssetsFile(scope.row.img1)]"
                preview-teleported
                :initial-index="4"
                fit="cover"
              ></el-image>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          prop="name"
          label="商品名称"
          width="110"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="price"
          label="商品价格"
          width="90"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="k.kg_kg"
          label="商品重量"
          width="80"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="date"
          label="生产日期"
          width="110"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="xx"
          label="信息"
          width="178"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="num"
          label="数量"
          width="60"
          align="center"
        ></el-table-column>
        <el-table-column label="多图" width="150" align="center">
          <template #default="scope">
            <div>
              <el-image
                style="width: 100px"
                :src="getAssetsFile(scope.row.img2)"
                :preview-src-list="[
                  getAssetsFile(scope.row.img2),
                  getAssetsFile(scope.row.img3),
                  getAssetsFile(scope.row.img4),
                ]"
                preview-teleported
              ></el-image>
            </div>
            <div>
              <el-image
                style="width: 100px"
                :src="getAssetsFile(scope.row.img3)"
              ></el-image>
            </div>
            <div>
              <el-image
                style="width: 100px"
                :src="getAssetsFile(scope.row.img4)"
              ></el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sj" label="(上/下架)" width="126" align="center">
          <template #default="{ row }">
            <el-switch
              class="ml-2"
              v-model="row.sj"
              width="88px"
              @change="handleStatusChange(row)"
              style="
                --el-switch-on-color: #13ce66;
                --el-switch-off-color: #ff4949;
              "
              inline-prompt
              active-text="已上架"
              inactive-text="已下架"
            />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center">
          <template #default="scope">
            <el-button
              text
              :icon="Edit"
              @click="handleEdit(scope.$index, scope.row)"
            >
              编辑
            </el-button>
            <el-button
              :icon="Delete"
              class="red"
              @click="handleDelete(scope.row.id, scope.$index)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
        <el-button type="danger" :icon="Delete" @click="deleteData"
          >批量删除</el-button
        >
        <el-button type="primary" :icon="UploadFilled" @click="importData"
          >导入</el-button
        >
        <el-button type="primary" :icon="Download" @click="exportData"
          >导出</el-button
        >
        <el-button type="primary" :icon="Plus" @click="saveStudent1"
          >新增</el-button
        >
      </div>
    </div>

    <!-- 添加/修改弹出框 -->
    <el-dialog :title="title" v-model="editVisible" width="30%">
      <el-form label-width="70px">
        <el-form-item label="商品名">
          <el-input v-model="formdata.name"></el-input>
        </el-form-item>
        <el-form-item label="重量">
          <el-select v-model="formdata.kg" placeholder="请选择重量">
            <el-option
              v-for="item in k"
              :key="item.id"
              :label="item.kg_kg"
              :value="item.kg_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="生产日期">
          <el-date-picker
            v-model="formdata.date"
            type="date"
            value-format="YYYY-MM-DD"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="formdata.price"></el-input>
        </el-form-item>
        <el-form-item label="数量">
          <el-input type="number" v-model="formdata.num"></el-input>
        </el-form-item>
        <el-input
          v-model="formdata.xx"
          :rows="2"
          type="textarea"
          placeholder="商品详情"
        />
        <el-form-item label="商品图片">
          <input type="file" @change="selectFile($event)" />
        </el-form-item>
        <el-form-item label="商品多图">
          <el-upload
            limit="15"
            mutiple
            v-model:file-list="fileList"
            action="http://127.0.0.1:1234/upfile/files"
            list-type="picture-card"
            :auto-upload="false"
            :on-success="success_file"
            :on-change="handleChange"
            :on-preview="handlepictureCardpreview"
            :on-remove="handleR"
            ref="uploadRef"
          >
            <el-icon>
              <plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveEdit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="basetable">
import { ref, reactive, computed } from "vue";
import {
  ElMessage,
  ElMessageBox,
  UploadProps,
  UploadUserFile,
} from "element-plus";
import {
  Delete,
  Edit,
  Search,
  Plus,
  UploadFilled,
  Download,
} from "@element-plus/icons-vue";
import {
  comStrPager,
  addShang,
  deleteSp,
  upStudent,
  deleteStudents,
  importExcel,
  file_,
  upSj,
} from "../api/student";
import { getAssetsFile } from "../assets/i";
import { getAllKg } from "../api/kg";
import { getAllImg } from "../api/image/image";

const as = [
  "http://localhost:5173/src/assets/image/1.jpg",
  "http://localhost:5173/src/assets/image/2.jpg",
  "http://localhost:5173/src/assets/image/3.jpg",
  "http://localhost:5173/src/assets/image/4.jpg",
];
const query = reactive({
  pageIndex: 1,
  pageSize: 150,
});
const tableData: any = ref([]);
const pageTotal = ref(0);

let com = reactive({
  id: "",
  name: "",
  price: "",
  kg: "",
  img1: "",
  img2: "",
  img3: "",
  img4: "",
  date: "",
  xx: "",
  num: "",
  sj: "",
  k: { id: "", kg_kg: "", kg_id: "" },
  image: {
    image2: "",
    image3: "",
    image4: "",
    image5: "",
    image6: "",
    image7: "",
  },
});

// 获取表格数据
const getCom = () => {
  comStrPager(query, com).then((res) => {
    tableData.value = res.data.list;
    pageTotal.value = res.data.pageTotal || 50;
    query.pageIndex = res.data.pageNum;
    query.pageSize = res.data.pageSize;
  });

  const myObj = JSON.stringify(tableData);
  console.log(JSON.parse(myObj));
};
const handleStatusChange = (product: any) => {
  // 处理状态变更，可以在这里发送请求更新服务器端的数据
  //修改学生信息
  upSj(product)
    .then((res) => {
      if (res.data === 1) {
        if (product.sj == 1) {
          ElMessage.success("上架成功！");
          //getCom();
        } else {
          ElMessage({
            showClose: true,
            message: "已下架",
          });
        }
      } else {
        ElMessage.error("上架失败！");
      }
    })
    .catch((error) => ElMessage.error(error));
  console.log(
    `商品 ${product.name} 状态变更为 ${product.sj ? "上架" : "下架"}`
  );
};
// const value2 = ref(true);
// const value3 = ref(0);
// // 计算属性，用于获取产品1的上下架状态
// const product1Status = computed(() => {
//   const sjValues = tableData.value.map((item) => item.sj);
//   // 遍历输出数组中的每个值
//   sjValues.forEach((value, index) => {
//     console.log(`${index + 1}:`, value);
//     value3.value = value;
//     console.log(value3.value);
//   });
//   return value3.value == 0 ? (value2.value = true) : (value2.value = false);
// });
getCom();
// 查询操作
const handleSearch = () => {
  getCom();
};
// 分页导航
const handlePageChange = (val: number) => {
  query.pageIndex = val;
  getCom(query);
};

// 删除操作
const handleDelete = (id: string, index: number) => {
  // 二次确认删除
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    type: "warning",
  }).then(() => {
    deleteSp(id)
      .then((res) => {
        if (res.data === 1) {
          ElMessage.success("删除成功！");
          //移除表格中的当前行，不用重新刷新数据
          tableData.value.splice(index, 1);
        } else {
          ElMessage.error("删除失败！");
        }
      })
      .catch((error) => ElMessage.error(error));
  });
};

// 表格编辑时弹窗和保存
const editVisible = ref(false);
const title = ref("");
let k: any = ref([]);
let image: any = ref([]);
// const saveStudent1 = ref(false);
// const disabled = ref(true)

const uploadRef: any = ref(null);
const dialogImageUrl = ref("");
const dialogvisible = ref(false);

const fileList = ref<UploadUserFile[]>([]);
//移除图片
const handleR: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {};
const handlepictureCardpreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogvisible.value = true;
  editVisible.value = true;
};
//获取后端传回来的图片名称
const handleChange = (file: any, fileList: any) => {
  for (let i = 0; i < fileList.length; i++) {
    const imgkey = `img${i + 1}`;
    formdata[imgkey] = fileList[i].response;
  }
};
//回调
const success_file = (res: any, file: any) => {
  if (res) {
  } else {
  }
};

getAllKg()
  .then((res) => {
    k.value = res.data;
  })
  .catch((err) => alert(err));

getAllImg()
  .then((res) => {
    image.value = res.data;
  })
  .catch((err) => alert(err));

//保存学生,完成新增与编辑功能
function saveStudent1() {
  if (k.value.length <= 0) {
    getAllKg()
      .then((res) => {
        k.value = res.data;
        title.value = "修改商品";
        Object.assign("null");
        editVisible.value = true;
      })
      .catch((err) => alert(err));
  } else {
    title.value = "添加商品";
    editVisible.value = true;
  }
}

const handleEdit = (index: number, row: any) => {
  title.value = "修改商品";
  // 检查row对象是否包含img字段，并且值不为空
  if (row.hasOwnProperty("img") && row.img !== null) {
    formdata.img = row.img; // 将原有的图片信息赋值给表单数据对象的相应属性
  } else {
    formdata.img = ""; // 如果原有图片信息不存在，则将img属性置为空
  }
  Object.assign(formdata, row);
  editVisible.value = true;
};

var file = "";
const selectFile = (event: any) => {
  file = event.target.files[0];
  console.log(file);
};
let formdata: any = reactive({});
let form_data = new FormData();
//添加/修改
async function saveEdit() {
  try {
    await uploadRef.value.submit();
    setTimeout(async () => {
      form_data.append("file", file);
      if (title.value === "添加商品") {
        const res = await file_(form_data);
        formdata.img = res.data;
        const addRes = await addShang(formdata);
        if (addRes.data === 1) {
          ElMessage({
            message: "新添加商品成功！",
            type: "success",
          });
          editVisible.value = false;
          formdata.data = {};
          getCom();
        } else {
          ElMessage.error("新添加商品失败！");
        }
      } else {
        const res = await file_(form_data);
        formdata.img = res.data;
        const updateRes = await upStudent(formdata);
        if (updateRes.data === 1) {
          ElMessage.success("修改成功！");
          editVisible.value = false;
          formdata.data = {};
          getCom();
        } else {
          ElMessage.error("修改失败！");
        }
      }
    }, 1);
  } catch (error: any) {
    ElMessage.error(error);
  }
}
// const saveEdit = () => {
//   if (title.value === "添加商品") {
//     // formdata.value.close();
//     //添加学生
//     form_data.append("file", file);
//     file_(form_data).then((res) => {
//       formdata.img = res.data;
//       addShang(formdata).then((res) => {
//         if (res.data === 1) {
//           ElMessage({
//             message: "新添加商品成功！",
//             type: "success",
//           });
//           getCom();
//           editVisible.value = false;
//           formdata.value = {};
//         } else {
//           ElMessage.error("新添加商品失败！");
//         }
//       });
//     });
//   } else if (title.value === "修改商品") {
//     // disabled.value = true
//     form_data.append("file", file);
//     file_(form_data).then((res) => {
//       formdata.img = res.data;
//       //修改学生信息
//       upStudent(formdata)
//         .then((res) => {
//           if (res.data === 1) {
//             ElMessage.success("修改成功！");
//             getCom();
//             editVisible.value = false;
//           } else {
//             ElMessage.error("修改失败！");
//           }
//         })
//         .catch((error) => ElMessage.error(error));
//     });
//   }
// };

const multipleSelection = ref([]);
//批量删除
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val;
  console.log(val);
};
const deleteData = () => {
  if (multipleSelection.value.length <= 0) {
    ElMessage.error("请至少选择一项进行删除！");
    return;
  } else {
    //二次确认删除
    ElMessageBox.confirm("确定要删除吗？", "提示", {
      type: "warning",
    }).then(() => {
      const ids: string[] = [];
      multipleSelection.value.forEach((item: any) => {
        ids.push(item.id);
      });
      deleteStudents(ids)
        .then((res) => {
          if (res.data >= 1) {
            ElMessage.success(`成功删除${res.data}!`);
            getCom();
          } else {
            ElMessage.error("删除失败！");
          }
        })
        .catch((error) => ElMessage.error(error));
    });
  }
};

let fileInput: any = null;
//导入
const importData = () => {
  if (!fileInput) {
    //创建一个input在页面上
    fileInput = document.createElement("input");
    fileInput.setAttribute("type", "file");
    fileInput.setAttribute("hidden", "true");
    fileInput.setAttribute("name", "file");
    document.body.appendChild(fileInput);

    //触发文件上传
    fileInput.addEventListener(
      "change",
      function (e: any) {
        //获取当前要上传的文件
        const file = e.target.files[0];
        //创建要上传的表单数据
        const formDate = new FormData();
        formDate.append("file", file);

        importExcel(formDate)
          .then((res) => {
            ElMessage.success("上传数据成功，添加了" + res.data + "行数据！");
            getCom();
          })
          .catch((err) => ElMessage.error(err));
      },
      true
    );
  }
  fileInput.value;
  fileInput.click();
};
//导出
const exportData = () => {
  const c = com;
  let url = "http://127.0.0.1:1234/C/exportExcel";
  url += `?&id=${c.id}&name=${c.name}&price=${c.price}&kg=${c.kg}&img1=${c.img1}&date=${c.date}&xx=${c.xx}&num=${c.num}&img1=${c.img1}&img2=${c.img2}&img3=${c.img3}`;
  location.href = url;
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-input {
  width: 14%;
}

.table {
  width: 100%;
  font-size: 14px;
}
.red {
  background: #f56c6c;
  color: white;
}

.mr10 {
  margin-right: 10px;
}
</style>
